package com.atldy.commerce;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.atldy.commerce.enums.CommonConstant;
import com.atldy.commerce.vo.LoginUserinfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;

/**
 * @version 1.0
 * @Author: lidongyang
 * @CreateTime: 2021-08-02 22:16
 * @Description： 解析token工具类，做鉴权使用
 */
public class JWTUtils {


    //从jwt token中解析用户登录信息
    public static LoginUserinfo parsingToken(String token) throws Exception {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        //获取负载
        Jws<Claims> claimsJws = parseToken(token, getPublicKey());
        Claims body = claimsJws.getBody();
        if (body.getExpiration().before(Calendar.getInstance().getTime())) {
            return null;
        }
        String result = body.get(CommonConstant.JWT_TOKEN_USER_INFO).toString();
        return JSONUtil.toBean(JSONUtil.toJsonStr(result), LoginUserinfo.class);
    }

    //获取polard负载的参数
    private static Jws<Claims> parseToken(String token, PublicKey publicKey) {
        return Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token);
    }

    //获取公钥
    private static PublicKey getPublicKey() throws Exception {
        X509EncodedKeySpec keySpec =
                new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(CommonConstant.PUBLIC_KEY));
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }

}